package com.sg.record.web;


import java.lang.reflect.InvocationTargetException;
import java.math.BigInteger;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Formatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.druid.sql.ast.SQLObject;
import com.alibaba.fastjson.JSONArray;
import com.sg.common.login.entity.Member;
import com.sg.common.empty.core.ConditionRes;
import com.sg.common.empty.core.Conditions2;
import com.sg.common.empty.core.EpUtil;
import com.sg.common.empty.core.FilterVal;
import com.sg.common.empty.core.Params2;
import com.sg.common.empty.service.CfgService;
import com.sg.common.login.service.OrgMemberService;
import com.sg.common.utils.CollUtil;
import com.sg.common.utils.Constant;
import com.sg.common.utils.DateTimeUtils;
import com.sg.common.utils.ReUtils;

@Repository
@Controller
@RequestMapping(value = "/api")
public class FundApiController {
	private Logger logger = Logger.getLogger(getClass());

	@Autowired
	CfgService service;
	
	@Autowired
	OrgMemberService omService;

	@RequestMapping(value = "/record/fund/fundList")
	@ResponseBody
	public Object findPlanList(HttpServletRequest request,
			@RequestBody Map<String, Object> requestBody) throws Exception {
		long s = System.currentTimeMillis();
//		System.out.println("requestBody:    "+requestBody);
		
		String route = (String) request.getAttribute("conf.route");
		// TODO 如果有js，使用js确定使用哪个sql
		Conditions2 condis = Conditions2.init(request, requestBody);
//		HttpSession session = request.getSession();
//		List<String> myRoles = (List<String>) session
//				.getAttribute(Constant.SESSION_MYROLES_CODE);
//		Boolean canSeeAll = false;
//		if (CollUtil.isNotEmpty(myRoles)) {
//			for (String myRole : myRoles) {
//				String TRI001 = "TRI001";		//TRI001,企划部综合管理员与人教部教培科人员,可以看到所有部门中心培训计划/实际
//				if (StringUtils.equals(myRole, TRI001)) {
//					canSeeAll = true;
//					break;
//				}
//			}
//		}
//		if (canSeeAll) {
//			session.setAttribute(Constant.SESSION_MYDEPORG, null);
//		}

		ConditionRes cr = condis.buildCon();
		String sorts = condis.buildSorts();                                                                                                             
		String limit = condis.buildLimit();

		// 替换
		String orancsql = Constant.get(route + ".csql");
		String oransql = Constant.get(route + ".sql");
		orancsql = orancsql.replace("@conditions", cr.getSql()).replace(
				"@orderby", sorts);
		oransql = oransql.replace("@conditions", cr.getSql())
				.replace("@orderby", sorts).replace("@limit", limit);

		List<Object> countList = service.queryBySql(orancsql, cr.getParams());
		String res = Constant.get(route + ".res");
		List<Map<String, Object>> dataList = service.queryBySqlToMap(oransql,
				cr.getParams(), res.split(","));
		
		System.out.println(dataList);
		
//		List<Map<String, Object>> planList = new ArrayList<Map<String, Object>>();
		
//		System.out.println(planList);
		

		int count = ((BigInteger) countList.get(0)).intValue();
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("items", dataList);
		map.put("total", count);
		map.put("code", 2000);
		long e = System.currentTimeMillis();
		System.out.println(e - s);
		return map;
	}
	
	
//	@RequestMapping(value = "/record/fund/add")
//	@ResponseBody
//	public Object add(HttpServletRequest request,@RequestBody Map<String, Object> requestBody) throws Exception {
//		String route = (String) request.getAttribute("conf.route");
//
//		String oransql = Constant.get(route + ".sql");
//		List<String> sqlParams = Params2.init(request,requestBody,service).build();
//		service.excuteBySql(oransql, sqlParams.toArray());
//
//		Map<String, Object> map = new HashMap<String, Object>();
//		Map<String, Object> item = new HashMap<String, Object>();
//		item.put("id", sqlParams.get(0));
//		map.put("item", item);
//		map.put("code", 2000);
//		return map;
//	}
	
	
	@RequestMapping(value = "/record/fund/add")
	@ResponseBody
	public Object add(HttpServletRequest request,
			@RequestBody Map<String, Object> requestBody) throws Exception{
		String route = (String) request.getAttribute("conf.route");
		
//		ArrayList enable = (ArrayList)requestBody.get("enable");
		//盘点类型为日盘点时，需查找上一个班已完成交接班的日志,   查找相同班组下，已完成交接班的，且创建日期最近的日志   ①未找到，本站应有金额及站存金额直接赋值5000   ②找到后，本站应有金额及站存金额=上一个班的站存金额
		String type = requestBody.get("type").toString();
		if(type.equals("0")){
//			
			//找上一个班已完成交接班的日志,
			Conditions2 condis = Conditions2.init(request, requestBody);
			ConditionRes cr = condis.buildCon();
			String sorts = condis.buildSorts();
			String limit = condis.buildLimit();

			// 替换
			String oransmonSql = Constant.get(route + ".smonSql");
			oransmonSql = oransmonSql.replace("@conditions", cr.getSql()).replace("@orderby", sorts).replace("@limit", limit);
			
			List<Object> countList = service.queryBySql(oransmonSql, cr.getParams());
			
//			&& !countList.isEmpty()
//			System.out.print("        "+countList+"      99999       ");
			
			if(countList==null){
				//未找到，本站应有金额及站存金额直接赋值5000
				requestBody.put("smon", 5000.0); 
			}else{
				//找到后，本站应有金额及站存金额=上一个班的站存金额
				String smon = (countList.get(0)).toString();
				requestBody.put("smon", smon);
			}
			
			String oransql = Constant.get(route + ".rsql");
			List<String> sqlParams = Params2.init(request,requestBody,service).build();
			service.excuteBySql(oransql, sqlParams.toArray());

			Map<String, Object> map = new HashMap<String, Object>();
			Map<String, Object> item = new HashMap<String, Object>();
			item.put("id", sqlParams.get(0));
			map.put("item", item);
			map.put("code", 2000);
			return map;
		}else{
			String oransql = Constant.get(route + ".ysql");
			List<String> ps = Constant.getStringList(route + ".yparams");
			List<String> sqlParams = Params2.init(request,requestBody,service).build(ps);
			service.excuteBySql(oransql, sqlParams.toArray());

			Map<String, Object> map = new HashMap<String, Object>();
			Map<String, Object> item = new HashMap<String, Object>();
			item.put("id", sqlParams.get(0));
			map.put("item", item);
			map.put("code", 2000);
			return map;
		}
	}
	
	
	/**
	 * 应急备用金，月度盘点时，区域站长手动清点确认
	 * @param request
	 * @return
	 * @throws IllegalAccessException
	 * @throws InvocationTargetException
	 * @throws NoSuchMethodException
	 */
	@RequestMapping(value = "/record/fund/checkfund", method = RequestMethod.POST)
	@ResponseBody
	public Object checkfund(HttpServletRequest request,
			@RequestBody Map<String, Object> requestBody) throws Exception{
		String route = (String) request.getAttribute("conf.route");
		
		Map<String, Object> map = new HashMap<String, Object>();
		if(requestBody.get("enable").toString().equals("1")){
			if (StringUtils.equalsIgnoreCase(requestBody.get("createCode").toString(), requestBody.get("memCode").toString())) {//限定,日志创建人与账户登录人,必须为同一人！
				if (!StringUtils.equalsIgnoreCase(requestBody.get("confirmCode").toString(), requestBody.get("memCode").toString())) { // 接班时，必须清点人与当前登录账户不同(与日志创建账户不同)
					Member m = omService.confirmMember(requestBody.get("confirmCode").toString(),requestBody.get("confirmPass").toString());
					
					List<String> myRoles =  EpUtil.findRemoteRoles(request, requestBody.get("confirmCode").toString());
//					System.out.printf("myRoles   :  000000000000         "+myRoles.indexOf("REC002")+"           ::           "+myRoles);
					
					if(m!=null){
						if(myRoles.indexOf("REC001") > -1 || myRoles.indexOf("REC002") > -1 || myRoles.indexOf("REC005") > -1){

							//得到接班人的id
							Conditions2 condis = Conditions2.init(request, requestBody);
							ConditionRes cr = condis.buildCon();
							String sorts = condis.buildSorts();
							String limit = condis.buildLimit();
							String idsql = Constant.get(route + ".idsql");
							idsql = idsql.replace("@conditions", cr.getSql()).replace("@orderby", sorts).replace("@limit", limit);
							
							List<Object> MemberId = service.queryBySql(idsql, cr.getParams());
							
							String confirmId = MemberId.get(0).toString();
							requestBody.put("confirmId", confirmId);
							
							String oransql = Constant.get(route + ".sql");
							List<String> sqlParams = Params2.init(request,requestBody,service).build();
							try {
								service.excuteBySql(oransql, sqlParams.toArray());
								map.put("code", 2000);
							} catch (Exception e) {
								logger.error(e.getMessage());
								map.put("code", 5030);
								map.put("msg", "更新发生内部错误，请联系管理员");
							}
							
						
						}else{
							map.put("code", 5000);
							map.put("msg", "该账号没有清点权限，请联系区域站长清点");
						}
					}else{
						map.put("code", 5000);
						map.put("msg", "该账号不存在");
					}
				}else{
					map.put("code", 5000);
					map.put("msg", "日志创建人与清点人不能为同一人，日志创建人工号："+requestBody.get("createCode").toString()+", 当前清点确定人工号："+requestBody.get("confirmCode").toString());
				}

			}else{
//				logger.error("");
				map.put("code", 5000);
				map.put("msg", "日志创建人与当前登录人必须为同一人，日志创建人工号："+requestBody.get("createCode").toString()+", 当前系统登录人工号："+requestBody.get("memCode").toString());
			}
			
		}else{
//			logger.error("");
			map.put("code", 5000);
			map.put("msg", "不能完成清点确认，请确认该应急备用金为新建状态");
			
		}
		return map;
	}

}
